<?php
/**
 * 考试项目管理页面 - 精确定位版
 * 功能：展示、删除考试项目，支持AJAX操作，进度统计和筛选
 * 权限：仅考试项目管理员可访问
 */

// 开启会话
session_start();

// 检查AJAX删除请求 - 独立处理，避免HTML输出污染JSON响应
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    // AJAX请求：不包含navigation.php，直接处理
    require_once 'database.php';

    $response = ['success' => false, 'message' => '删除失败'];

    try {
        // 检查用户是否已登录
        if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
            $response['message'] = '用户未登录';
            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }

        $current_user_id = $_SESSION['user_id'];
        $exam_id = intval($_POST['exam_id'] ?? 0);

        if ($exam_id <= 0) {
            $response['message'] = '无效的项目ID';
            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }

        // 获取用户角色进行权限验证
        $roles = [];
        $role_sql = "SELECT role FROM user_roles WHERE user_id = ?";
        $role_stmt = $conn->prepare($role_sql);
        if ($role_stmt) {
            $role_stmt->bind_param("s", $current_user_id);
            $role_stmt->execute();
            $role_result = $role_stmt->get_result();
            while ($row = $role_result->fetch_assoc()) {
                $roles[] = $row['role'];
            }
            $role_stmt->close();
        }

        // 权限验证
        if (!in_array('考试项目管理员', $roles)) {
            $response['message'] = '权限不足：需要考试项目管理员权限';
            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }

        // 获取项目信息
        $select_sql = "SELECT exam_name FROM exams WHERE id = ?";
        $select_stmt = $conn->prepare($select_sql);
        if (!$select_stmt) {
            $response['message'] = '数据库查询准备失败';
            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }

        $select_stmt->bind_param("i", $exam_id);
        $select_stmt->execute();
        $select_result = $select_stmt->get_result();

        if ($select_result->num_rows === 0) {
            $select_stmt->close();
            $response['message'] = '项目不存在';
            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }

        $exam_data = $select_result->fetch_assoc();
        $exam_name = $exam_data['exam_name'];
        $select_stmt->close();

        // 执行删除
        $delete_sql = "DELETE FROM exams WHERE id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        if (!$delete_stmt) {
            $response['message'] = '删除语句准备失败';
            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }

        $delete_stmt->bind_param("i", $exam_id);

        if ($delete_stmt->execute()) {
            if ($delete_stmt->affected_rows > 0) {
                $response = [
                    'success' => true,
                    'message' => "项目「{$exam_name}」删除成功",
                    'deleted_id' => $exam_id,
                    'timestamp' => date('Y-m-d H:i:s')
                ];

                // 记录操作日志
                error_log("删除考试项目成功: ID={$exam_id}, 名称={$exam_name}, 操作者={$current_user_id}");
            } else {
                $response['message'] = '项目不存在或已被删除';
            }
        } else {
            $response['message'] = '删除操作失败：' . $delete_stmt->error;
        }

        $delete_stmt->close();

    } catch (Exception $e) {
        $response['message'] = '删除失败：' . $e->getMessage();
        error_log("删除考试项目失败: " . $e->getMessage() . " (用户: {$current_user_id})");
    }

    // 关闭数据库连接
    if (isset($conn)) {
        $conn->close();
    }

    // 纯JSON响应，避免HTML污染
    header('Content-Type: application/json');
    echo json_encode($response);
    exit(); // 立即退出，不输出HTML
}

// 非AJAX请求：正常页面处理
// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 为navigation.php设置必需变量
$current_user_id = $_SESSION['user_id'] ?? '';
$GLOBALS['current_user_id'] = $current_user_id;

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    $_SESSION['error_message'] = "数据库连接失败：" . $e->getMessage();
    header('Location: user_home.php');
    exit();
}

// 包含统一导航栏
if (file_exists('common/navigation.php')) {
    require_once 'common/navigation.php';
}

// 如果getUserRoles函数不存在，定义备用函数
if (!function_exists('getUserRoles')) {
    function getUserRoles($user_id, $conn) {
        $roles = [];
        try {
            $sql = "SELECT role FROM user_roles WHERE user_id = ?";
            $stmt = $conn->prepare($sql);

            if ($stmt) {
                $stmt->bind_param("s", $user_id);
                $stmt->execute();
                $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {
                    $roles[] = $row['role'];
                }
                $stmt->close();
            }
        } catch (Exception $e) {
            error_log("获取用户角色失败: " . $e->getMessage());
        }

        return $roles;
    }
}

// 权限验证 - 仅考试项目管理员可访问
$user_roles = getUserRoles($current_user_id, $conn);
if (!in_array('考试项目管理员', $user_roles)) {
    $_SESSION['error_message'] = "访问被拒绝：您需要考试项目管理员权限才能访问此页面";
    header('Location: access_denied.php');
    exit();
}

// 获取考试项目列表
$projects = [];
$error_message = '';
$success_message = $_SESSION['success_message'] ?? '';
unset($_SESSION['success_message']);

try {
    $sql = "SELECT 
                id, 
                exam_name, 
                exam_date, 
                end_date,
                subject_count,
                students_per_subject,
                rooms_per_subject,
                invigilators_per_subject,
                progress,
                status,
                created_by,
                created_at
            FROM exams 
            WHERE status = 'active' 
            ORDER BY created_at DESC";

    $result = $conn->query($sql);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $projects[] = $row;
        }
    } else {
        throw new Exception('查询考试项目失败: ' . $conn->error);
    }

} catch (Exception $e) {
    $error_message = $e->getMessage();
    error_log("获取考试项目列表失败: " . $error_message);
}

// 获取进度统计数据
$progress_stats = [];
try {
    $stats_sql = "SELECT progress, COUNT(*) as count, GROUP_CONCAT(id) as project_ids 
                  FROM exams 
                  WHERE status = 'active' 
                  GROUP BY progress 
                  ORDER BY progress";

    $stats_result = $conn->query($stats_sql);

    if ($stats_result) {
        while ($row = $stats_result->fetch_assoc()) {
            $progress_stats[intval($row['progress'])] = [
                'count' => intval($row['count']),
                'project_ids' => explode(',', $row['project_ids'])
            ];
        }
    }
} catch (Exception $e) {
    error_log("获取进度统计失败: " . $e->getMessage());
}

// 进度描述数组
$progress_descriptions = [
    1 => '新建考试项目',
    2 => '编排考场及预编排监考员',
    3 => '监考报名',
    4 => '编排监考员'
];

// 里程碑配置 - 精确位置定义
$milestones = [
    1 => ['title' => '新建考试项目', 'icon' => 'fas fa-plus-circle', 'position' => 0],
    2 => ['title' => '编排考场及预编排监考员', 'icon' => 'fas fa-users-cog', 'position' => 33.33],
    3 => ['title' => '监考报名', 'icon' => 'fas fa-user-check', 'position' => 66.67],
    4 => ['title' => '编排监考员', 'icon' => 'fas fa-clipboard-check', 'position' => 100]
];

$page_title = '考试项目管理 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        .main-content {
            margin-top: 20px;
            padding-bottom: 40px;
        }

        .page-header {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        /* 功能增强通知 */
        .enhancement-notice {
            background: linear-gradient(135deg, #e8f4fd 0%, #f0f8ff 50%, #e1f5fe 100%);
            border: 1px solid #81d4fa;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(33, 150, 243, 0.1);
        }

        .enhancement-notice h6 {
            color: #0277bd;
            font-weight: 700;
            margin-bottom: 12px;
            font-size: 16px;
        }

        .enhancement-notice .badge {
            background: linear-gradient(135deg, #2196f3 0%, #03a9f4 100%);
            color: white;
            margin-right: 8px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .enhancement-notice p {
            color: #01579b;
            margin: 0;
            line-height: 1.5;
        }

        .projects-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 30px;
        }

        .project-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            background: white;
        }

        .project-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }

        .project-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #495057;
            margin-bottom: 15px;
        }

        .project-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .info-item {
            display: flex;
            align-items: center;
            font-size: 14px;
        }

        .info-item i {
            margin-right: 8px;
            width: 16px;
            color: #6c757d;
        }

        /* 里程碑进度条样式 - 精确定位版 */
        .milestone-progress {
            position: relative;
            width: 100%;
            height: 60px;
            margin: 20px 0;
            padding: 0 20px;
        }

        .progress-track {
            position: absolute;
            top: 50%;
            left: 20px;
            right: 20px;
            height: 8px;
            transform: translateY(-50%);
            border-radius: 4px;
            background: linear-gradient(90deg, #dc3545 0%, #0d6efd 100%);
            overflow: hidden;
        }

        .progress-mask {
            position: absolute;
            top: 0;
            height: 100%;
            background: #e9ecef;
            transition: all 0.8s ease-in-out;
            border-radius: 4px;
        }

        .milestone-points {
            position: relative;
            display: flex;
            height: 60px;
            z-index: 2;
        }

        .milestone-point {
            position: absolute;
            display: flex;
            flex-direction: column;
            align-items: center;
            transform: translateX(-50%);
        }

        /* 精确定位里程碑 */
        .milestone-point:nth-child(1) { left: 0%; }
        .milestone-point:nth-child(2) { left: 33.33%; }
        .milestone-point:nth-child(3) { left: 66.67%; }
        .milestone-point:nth-child(4) { left: 100%; }

        .milestone-star {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            transition: all 0.3s ease;
            position: relative;
            z-index: 3;
            margin-top: 14px;
        }

        .milestone-star.completed {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 50%, #ffd700 100%);
            color: #fff;
            box-shadow: 0 0 20px rgba(255, 215, 0, 0.6);
            animation: starGlow 2s ease-in-out infinite alternate;
        }

        .milestone-star.pending {
            background: #6c757d;
            color: #fff;
        }

        .milestone-label {
            font-size: 11px;
            text-align: center;
            margin-top: 8px;
            max-width: 90px;
            line-height: 1.2;
            font-weight: 500;
        }

        .milestone-label.completed {
            color: #198754;
            font-weight: 600;
        }

        .milestone-label.pending {
            color: #6c757d;
        }

        @keyframes starGlow {
            0% {
                box-shadow: 0 0 20px rgba(255, 215, 0, 0.6);
                transform: scale(1);
            }
            100% {
                box-shadow: 0 0 30px rgba(255, 215, 0, 0.8);
                transform: scale(1.05);
            }
        }

        /* 美化统计区域 */
        .progress-stats {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            border: 1px solid #dee2e6;
            display: flex;
            flex-wrap: nowrap;
            gap: 15px;
            overflow-x: auto;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 3px 12px rgba(0,0,0,0.12);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 2px solid transparent;
            flex: 1;
            min-width: 160px;
            max-width: 200px;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #007bff, #6610f2);
            transform: scaleX(0);
            transition: transform 0.3s ease;
        }

        .stat-card:hover::before {
            transform: scaleX(1);
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.15);
        }

        .stat-card.active {
            border-color: #007bff;
            background: linear-gradient(135deg, #e3f2fd 0%, #f8f9fa 100%);
            transform: translateY(-2px);
        }

        .stat-card.active::before {
            transform: scaleX(1);
        }

        .stat-number {
            font-size: 2.2rem;
            font-weight: 800;
            margin-bottom: 8px;
            background: linear-gradient(135deg, #007bff, #6610f2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .stat-label {
            font-size: 13px;
            color: #495057;
            font-weight: 600;
            line-height: 1.3;
        }

        .stat-card-1 .stat-number {
            background: linear-gradient(135deg, #1976d2, #42a5f5);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .stat-card-2 .stat-number {
            background: linear-gradient(135deg, #f57c00, #ffb74d);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .stat-card-3 .stat-number {
            background: linear-gradient(135deg, #7b1fa2, #ba68c8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .stat-card-4 .stat-number {
            background: linear-gradient(135deg, #388e3c, #66bb6a);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* 筛选控制 */
        .filter-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .filter-info {
            color: #6c757d;
            font-size: 14px;
        }

        .clear-filter {
            background: #6c757d;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 13px;
            transition: all 0.3s ease;
        }

        .clear-filter:hover {
            background: #495057;
            color: white;
        }

        .progress-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-align: center;
            min-width: 120px;
        }

        .progress-1 { background-color: #e3f2fd; color: #1976d2; }
        .progress-2 { background-color: #fff3e0; color: #f57c00; }
        .progress-3 { background-color: #f3e5f5; color: #7b1fa2; }
        .progress-4 { background-color: #e8f5e8; color: #388e3c; }

        .project-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 10px;
            margin-top: 20px;
        }

        .btn-sm {
            padding: 8px 12px;
            font-size: 13px;
            border-radius: 6px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .btn-sm i {
            margin-right: 6px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        /* 隐藏被筛选的项目 */
        .project-card.filtered-out {
            display: none;
        }

        @media (max-width: 768px) {
            .project-info {
                grid-template-columns: 1fr;
            }

            .project-actions {
                grid-template-columns: 1fr;
            }

            .projects-container {
                padding: 20px;
            }

            .milestone-progress {
                padding: 0 15px;
            }

            .milestone-star {
                width: 28px;
                height: 28px;
                font-size: 14px;
            }

            .milestone-label {
                font-size: 10px;
                max-width: 70px;
            }

            .progress-stats {
                padding: 20px 15px;
                gap: 10px;
            }

            .stat-card {
                min-width: 140px;
                padding: 15px;
            }

            .stat-number {
                font-size: 1.8rem;
            }

            .filter-controls {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
</head>
<body>
<!-- 统一导航栏 -->
<?php
if (file_exists('common/navigation.php')) {
    include_once 'common/navigation.php';
} else {
    // 备用导航栏
    echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
                <div class="container">
                    <a class="navbar-brand" href="user_home.php">考务管理系统</a>
                    <div class="navbar-nav ms-auto">
                        <span class="navbar-text me-3">用户: ' . htmlspecialchars($current_user_id) . '</span>
                        <a class="nav-link" href="logout.php">退出登录</a>
                    </div>
                </div>
              </nav>';
}
?>

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 页面标题 -->
    <div class="page-header">
        <h1 class="mb-2">
            <i class="fas fa-clipboard-list"></i> 考试项目管理
        </h1>
        <p class="mb-0">管理和查看所有考试项目的详细信息</p>
    </div>

    <!-- 功能增强通知 -->
    <div class="enhancement-notice">
        <h6><i class="fas fa-rocket"></i> 精确定位里程碑系统</h6>
        <p>
            <span class="badge">ENHANCED</span>
            全新精确定位里程碑进度条，遮罩层与星星坐标完美重合，支持智能筛选和实时统计分析。
        </p>
    </div>

    <!-- 成功消息 -->
    <?php if (!empty($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 错误消息 -->
    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- 进度统计卡片 - 美化版 -->
    <div class="progress-stats">
        <div class="stat-card stat-card-all" onclick="filterByProgress('all')" data-progress="all">
            <div class="stat-number"><?php echo count($projects); ?></div>
            <div class="stat-label">全部项目</div>
        </div>
        <?php for ($i = 1; $i <= 4; $i++): ?>
            <div class="stat-card stat-card-<?php echo $i; ?>" onclick="filterByProgress(<?php echo $i; ?>)" data-progress="<?php echo $i; ?>">
                <div class="stat-number"><?php echo isset($progress_stats[$i]) ? $progress_stats[$i]['count'] : 0; ?></div>
                <div class="stat-label"><?php echo $progress_descriptions[$i]; ?></div>
            </div>
        <?php endfor; ?>
    </div>

    <!-- 筛选控制 -->
    <div class="filter-controls">
        <div>
            <h3 class="mb-0">项目列表</h3>
            <div class="filter-info" id="filterInfo">显示全部 <?php echo count($projects); ?> 个项目</div>
        </div>
        <div>
            <button class="clear-filter" onclick="clearFilter()" id="clearFilterBtn" style="display: none;">
                <i class="fas fa-times"></i> 清除筛选
            </button>
            <a href="create_exam_project.php" class="btn btn-success">
                <i class="fas fa-plus"></i> 新建考试项目
            </a>
        </div>
    </div>

    <!-- 项目列表容器 -->
    <div class="projects-container">
        <?php if (empty($projects)): ?>
            <!-- 空状态 -->
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <h4>暂无考试项目</h4>
                <p class="mb-3">还没有创建任何考试项目</p>
                <a href="create_exam_project.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 创建第一个项目
                </a>
            </div>
        <?php else: ?>
            <!-- 项目卡片列表 -->
            <?php foreach ($projects as $project): ?>
                <div class="project-card" data-project-id="<?php echo $project['id']; ?>" data-progress="<?php echo intval($project['progress']); ?>">
                    <!-- 项目标题 -->
                    <div class="project-title">
                        <i class="fas fa-clipboard-list"></i>
                        <?php echo htmlspecialchars($project['exam_name']); ?>
                    </div>

                    <!-- 里程碑进度条 - 精确定位版 -->
                    <div class="milestone-progress" data-progress="<?php echo intval($project['progress']); ?>">
                        <div class="progress-track">
                            <div class="progress-mask"></div>
                        </div>
                        <div class="milestone-points">
                            <?php foreach ($milestones as $step => $milestone): ?>
                                <div class="milestone-point">
                                    <div class="milestone-star <?php echo (intval($project['progress']) >= $step) ? 'completed' : 'pending'; ?>">
                                        <i class="fas fa-star"></i>
                                    </div>
                                    <div class="milestone-label <?php echo (intval($project['progress']) >= $step) ? 'completed' : 'pending'; ?>">
                                        <?php echo $milestone['title']; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- 项目信息 -->
                    <div class="project-info">
                        <div class="info-item">
                            <i class="fas fa-calendar-alt"></i>
                            <span>开始日期：<?php echo htmlspecialchars($project['exam_date']); ?></span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-calendar-check"></i>
                            <span>结束日期：<?php echo htmlspecialchars($project['end_date'] ?? '未设置'); ?></span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-book"></i>
                            <span>科目数量：<?php echo intval($project['subject_count']); ?> 门</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-users"></i>
                            <span>每科学生：<?php echo intval($project['students_per_subject']); ?> 人</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-door-open"></i>
                            <span>每科课室：<?php echo intval($project['rooms_per_subject']); ?> 间</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-user-tie"></i>
                            <span>每科监考：<?php echo intval($project['invigilators_per_subject']); ?> 人</span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-user"></i>
                            <span>创建者：<?php echo htmlspecialchars($project['created_by']); ?></span>
                        </div>
                        <div class="info-item">
                            <i class="fas fa-clock"></i>
                            <span>创建时间：<?php echo date('Y-m-d H:i', strtotime($project['created_at'])); ?></span>
                        </div>
                    </div>

                    <!-- 项目进度 -->
                    <div class="mb-3">
                            <span class="progress-badge progress-<?php echo intval($project['progress']); ?>">
                                阶段 <?php echo intval($project['progress']); ?>：<?php echo $progress_descriptions[intval($project['progress'])] ?? '未知阶段'; ?>
                            </span>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="project-actions">
                        <a href="exam_detail.php?id=<?php echo $project['id']; ?>" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-eye"></i> 查看详情
                        </a>
                        <a href="edit_exam_project.php?id=<?php echo $project['id']; ?>" class="btn btn-outline-secondary btn-sm">
                            <i class="fas fa-edit"></i> 编辑项目
                        </a>
                        <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $project['id']; ?>" class="btn btn-outline-info btn-sm">
                            <i class="fas fa-users-cog"></i> 编排考场及预编排监考员
                        </a>
                        <a href="signup_management.php?exam_id=<?php echo $project['id']; ?>" class="btn btn-outline-success btn-sm">
                            <i class="fas fa-user-check"></i> 报名管理
                        </a>
                        <a href="invigilator_assignment.php?exam_id=<?php echo $project['id']; ?>" class="btn btn-outline-warning btn-sm">
                            <i class="fas fa-clipboard-check"></i> 编排监考员
                        </a>
                        <a href="violations_display.php?exam_id=<?php echo $project['id']; ?>" class="btn btn-outline-danger btn-sm">
                            <i class="fas fa-exclamation-triangle"></i> 违规管理
                        </a>
                        <button class="btn btn-outline-danger btn-sm" onclick="deleteProject(<?php echo $project['id']; ?>, '<?php echo htmlspecialchars($project['exam_name'], ENT_QUOTES); ?>')">
                            <i class="fas fa-trash"></i> 删除项目
                        </button>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    let currentFilter = 'all';

    // 里程碑位置映射 - 精确坐标
    const milestonePositions = {
        1: 0,      // 0%
        2: 33.33,  // 33.33%
        3: 66.67,  // 66.67%
        4: 100     // 100%
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('考试项目管理页面加载完成');
        initMilestoneProgress();
    });

    // 初始化里程碑进度条 - 精确定位版
    function initMilestoneProgress() {
        const progressBars = document.querySelectorAll('.milestone-progress');

        progressBars.forEach(bar => {
            const progress = parseInt(bar.dataset.progress);
            const mask = bar.querySelector('.progress-mask');

            // 精确计算遮罩起始位置
            // 遮罩从当前进度里程碑的精确位置开始
            const maskStartPosition = milestonePositions[progress] || 0;
            const maskWidth = 100 - maskStartPosition;

            // 设置遮罩位置和宽度
            mask.style.left = maskStartPosition + '%';
            mask.style.width = '0%'; // 初始宽度为0，用于动画

            // 延迟执行动画效果
            setTimeout(() => {
                mask.style.width = maskWidth + '%';
            }, 300);
        });

        // 添加星星悬停效果
        const stars = document.querySelectorAll('.milestone-star.completed');
        stars.forEach(star => {
            star.addEventListener('mouseenter', function() {
                this.style.transform = 'scale(1.2)';
                this.style.boxShadow = '0 0 30px rgba(255, 215, 0, 0.9)';
            });

            star.addEventListener('mouseleave', function() {
                this.style.transform = 'scale(1)';
                this.style.boxShadow = '0 0 20px rgba(255, 215, 0, 0.6)';
            });
        });
    }

    // 按进度筛选项目
    function filterByProgress(progress) {
        currentFilter = progress;
        const projectCards = document.querySelectorAll('.project-card');
        const statCards = document.querySelectorAll('.stat-card');
        const filterInfo = document.getElementById('filterInfo');
        const clearFilterBtn = document.getElementById('clearFilterBtn');

        // 更新统计卡片状态
        statCards.forEach(card => {
            card.classList.remove('active');
        });
        document.querySelector(`[data-progress="${progress}"]`).classList.add('active');

        let visibleCount = 0;

        // 筛选项目卡片
        projectCards.forEach(card => {
            const cardProgress = parseInt(card.dataset.progress);

            if (progress === 'all' || cardProgress === progress) {
                card.classList.remove('filtered-out');
                card.style.display = 'block';
                visibleCount++;
            } else {
                card.classList.add('filtered-out');
                card.style.display = 'none';
            }
        });

        // 更新筛选信息
        if (progress === 'all') {
            filterInfo.textContent = `显示全部 ${visibleCount} 个项目`;
            clearFilterBtn.style.display = 'none';
        } else {
            const progressDescriptions = {
                1: '新建考试项目',
                2: '编排考场及预编排监考员',
                3: '监考报名',
                4: '编排监考员'
            };
            filterInfo.textContent = `筛选：${progressDescriptions[progress]} (${visibleCount} 个项目)`;
            clearFilterBtn.style.display = 'inline-block';
        }

        // 添加筛选动画
        setTimeout(() => {
            const visibleCards = document.querySelectorAll('.project-card:not(.filtered-out)');
            visibleCards.forEach((card, index) => {
                card.style.opacity = '0';
                card.style.transform = 'translateY(20px)';

                setTimeout(() => {
                    card.style.transition = 'all 0.3s ease';
                    card.style.opacity = '1';
                    card.style.transform = 'translateY(0)';
                }, index * 50);
            });
        }, 100);
    }

    // 清除筛选
    function clearFilter() {
        filterByProgress('all');
    }

    // 删除项目 - 修复版
    function deleteProject(projectId, projectName) {
        Swal.fire({
            title: '确认删除',
            text: `确定要删除项目「${projectName}」吗？此操作不可撤销！`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '确定删除',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                // 显示加载状态
                Swal.fire({
                    title: '正在删除...',
                    text: '请稍候',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 发送AJAX删除请求
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('exam_id', projectId);

                fetch('exam_projects.php', {
                    method: 'POST',
                    body: formData
                })
                    .then(response => {
                        // 检查响应类型
                        const contentType = response.headers.get('content-type');
                        if (contentType && contentType.includes('application/json')) {
                            return response.json();
                        } else {
                            // 如果不是JSON，获取文本内容用于调试
                            return response.text().then(text => {
                                console.error('服务器返回非JSON响应:', text);
                                throw new Error('服务器返回格式错误');
                            });
                        }
                    })
                    .then(data => {
                        console.log('删除响应:', data);

                        if (data.success) {
                            // 删除成功
                            Swal.fire({
                                title: '删除成功',
                                text: data.message,
                                icon: 'success',
                                confirmButtonText: '确定'
                            }).then(() => {
                                // 移除对应的项目卡片
                                const projectCard = document.querySelector(`[data-project-id="${projectId}"]`);
                                if (projectCard) {
                                    projectCard.style.transition = 'all 0.3s ease';
                                    projectCard.style.opacity = '0';
                                    projectCard.style.transform = 'translateX(-100%)';

                                    setTimeout(() => {
                                        projectCard.remove();

                                        // 检查是否还有项目
                                        const remainingProjects = document.querySelectorAll('.project-card');
                                        if (remainingProjects.length === 0) {
                                            // 显示空状态
                                            location.reload();
                                        } else {
                                            // 更新筛选计数
                                            if (currentFilter !== 'all') {
                                                filterByProgress(currentFilter);
                                            } else {
                                                filterByProgress('all');
                                            }
                                        }
                                    }, 300);
                                }
                            });
                        } else {
                            // 删除失败
                            Swal.fire({
                                title: '删除失败',
                                text: data.message || '未知错误',
                                icon: 'error',
                                confirmButtonText: '确定'
                            });
                        }
                    })
                    .catch(error => {
                        console.error('删除请求失败:', error);
                        Swal.fire({
                            title: '网络错误',
                            text: '删除请求失败，请检查网络连接',
                            icon: 'error',
                            confirmButtonText: '确定'
                        });
                    });
            }
        });
    }
</script>

<?php
// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>
</body>
</html>